package cn.fl.ref.interestmanagement.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPayRegVO;
import cn.fl.ref.interestmanagement.service.IInterestManagementService;
import cn.fl.ref.interestmanagement.transfrom.InterestManagementVOTransform;
import cn.fl.ref.interestmanagement.vo.InterestManagementVO;
import fl.ref.bscrateinfo.dto.BscRateInfoDTO;
import fl.ref.bscrateinfo.service.IBscRateInfoApiService;
import fl.ref.fncprjpaysch.dto.FncPrjPayRegDTO;
import fl.ref.fncprjpaysch.service.IFncPrjPaySchApiService;
import fl.ref.interestmanagement.condition.InterestmanagementQueryCondition;
import fl.ref.interestmanagement.constant.InterestManagementConstant;
import fl.ref.interestmanagement.dto.FncPrjPayRegInfoDTO;
import fl.ref.interestmanagement.dto.InterestManagementDTO;
import fl.ref.interestmanagement.service.IInterestManagementApiService;

@Service
public class InterestManagementServiceImpl implements IInterestManagementService {

	private static final Logger logger = LoggerFactory.getLogger(InterestManagementServiceImpl.class);
		
	@Autowired
	private IInterestManagementApiService interestManagementApiService;
	
	@Autowired
	private IFncPrjPaySchApiService fncPrjPaySchApiService;
	
	@Autowired
	private IBscRateInfoApiService bscRateInfoApiService;
	
	
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 * 分页查询所有
	 * @param page
	 * @return
	 */	
	@Override
	@SuppressWarnings("unchecked")
	public Pager searchListPage(Pager page) throws BaseException {
		if(null == page){
			page = new Pager();
			return page;
		}
		Pager resultPager = this.interestManagementApiService.searchListPage(page);
		List<InterestManagementDTO> dto = (List<InterestManagementDTO>)resultPager.getResultList();
		InterestmanagementQueryCondition condition = (InterestmanagementQueryCondition)resultPager.getCondition();
		if(CollectionUtils.isNotEmpty(dto)){
			List<InterestManagementDTO> dtoList;
			try {
				dtoList = this.setInterestManagementInfo(dto,condition.getSysCd(),condition.getOrgCd());
				resultPager.setResultList(dtoList);
			} catch (NumberFormatException | ParseException e) {
				e.printStackTrace();
			}
		}
		
		return resultPager;
	}
	
	//数据字典赋值
	private List<InterestManagementDTO> setInterestManagementInfo(List<InterestManagementDTO> list, String sysCd, String orgCd) throws NumberFormatException, ParseException{
		List<InterestManagementDTO> dtoList = new ArrayList<InterestManagementDTO>();
		BscRateInfoDTO bscRateInfoDTO = new BscRateInfoDTO();
		long bscRateId = 0;		//基础利率表id
		int num = 0;
		//获取调息方式
		Map<String, String> intRatTypeList = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, InterestManagementConstant.INTEREST_MANAGEMENT_INT_RAT_TYPE);
		//获取调试未到期配置天数
		Map<String, String> undueTimeList = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, InterestManagementConstant.INTEREST_UNDUE_TIME);
		for(InterestManagementDTO dto : list){
			//调息方式
			if(intRatTypeList.containsKey(String.valueOf(dto.getIntRatType()))){
				dto.setIntRatTypeNm(intRatTypeList.get(String.valueOf(dto.getIntRatType())));
			}
			if(dto.getBscRateId() != null && (dto.getThIntRat() == null || dto.getThIntTm() == null)){
				if(bscRateId == 0){
					bscRateId = dto.getBscRateId();
					bscRateInfoDTO = this.bscRateInfoApiService.getNextBscRateInfoById(dto.getBscRateId());
				}else if(bscRateId != dto.getBscRateId()){
					bscRateInfoDTO = this.bscRateInfoApiService.getNextBscRateInfoById(dto.getBscRateId());
				}
			}else if((dto.getRegId() == null) && num == 0){
				//获取靠近当前时间的基础利率信息
				bscRateInfoDTO = this.bscRateInfoApiService.getBscRateInfo();
				num++;
			}
			if(bscRateInfoDTO == null){
				dto.setIsPranayama(0);
			}else{
				//判断是否需要从基础利率表获取本次调息利率和本次调试时间
				if(dto.getThIntRat() == null || dto.getThIntTm() == null){
					if(dto.getNumberOfPeriods() > 0 && dto.getNumberOfPeriods() <= 6){		//半年
						dto.setThIntRat(bscRateInfoDTO.getHalfY());
					}else if(dto.getNumberOfPeriods() > 6 && dto.getNumberOfPeriods() <= 12){	//一年
						dto.setThIntRat(bscRateInfoDTO.getOneY());
					}else if(dto.getNumberOfPeriods() > 12 && dto.getNumberOfPeriods() <= 36){	//三年
						dto.setThIntRat(bscRateInfoDTO.getThreeY());
					}else if(dto.getNumberOfPeriods() > 36 && dto.getNumberOfPeriods() <= 60){	//五年
						dto.setThIntRat(bscRateInfoDTO.getFiveY());
					}else if(dto.getNumberOfPeriods() > 60){		//五年以上
						dto.setThIntRat(bscRateInfoDTO.getMoreY());
					}else if(dto.getNumberOfPeriods() < 1){			//没有还款记录
						dtoList.remove(dto);
					}
					dto.setThIntTm(bscRateInfoDTO.getMdfTm());
					dto.setBscRateId(bscRateInfoDTO.getId());
					dto.setIsPranayama(1);
				}
			}
			//设置调息到期时间
			int n = 1;
			if(dto.getThIntTm() != null){
				n = setInserestUndueTime(dto.getThIntTm(),Integer.parseInt(undueTimeList.get("0")));
			}
			dto.setUndueTimeType(n);
			dtoList.add(dto);
		}
		return dtoList;
	}
	
	/**
	 * 设置调息提醒
	 * @param inserestDate
	 * @return
	 * @throws ParseException 
	 */
	private int setInserestUndueTime(Date undueDate, Integer undueDateNum) throws ParseException{
		Date nowDate = DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD);
		Date inserestDate = DateUtils.formatDate(undueDate, DateUtils.YYYY_MM_DD); 
        Calendar cal = Calendar.getInstance();    
        cal.setTime(nowDate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(inserestDate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
        Integer num = Integer.parseInt(String.valueOf(between_days));     
		if(num < 0){
			return 3;		//已过期
		}
        if(num >= undueDateNum){
			return 1;		//未到期
		}else{
			return 2;		//即将到期
		}
	}

	/**
	 * 根据支付ID查询还款信息
	 * @param paySchId
	 * @return
	 * @throws BaseException
	 */
	@Override
	public InterestManagementVO getById(Long paySchId, String sysCd, String orgCd) throws BaseException {
		if(StringUtils.isEmpty(paySchId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		InterestManagementDTO dto = interestManagementApiService.getById(paySchId, sysCd, orgCd);
		List<InterestManagementDTO> list = new ArrayList<InterestManagementDTO>();
		list.add(dto);
		try {
			InterestManagementDTO setDTO  = this.setInterestManagementInfo(list, sysCd, orgCd).get(0);
			InterestManagementVO vo = new InterestManagementVO();
			if(null != setDTO){
				vo = InterestManagementVOTransform.toVO(setDTO);
			}
			return vo;
		} catch (NumberFormatException | ParseException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	/**
	 * 保存支付调息表信息
	 * @param regDto
	 * @return
	 * @throws BaseException
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Long insertPayRegInfo(FncPrjPayRegInfoDTO reg) throws BaseException {
		//根据支付id得到项目相关信息
		Pager page = new Pager();
		page.setCurrentPage(1);
		page.setEveryPage(10);
		InterestmanagementQueryCondition condition = new InterestmanagementQueryCondition();
		condition.setId(Long.valueOf(0));
		condition.setPayId(reg.getPayId());
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(condition);
		Pager resultPager = this.interestManagementApiService.searchListPage(page);
		List<InterestManagementDTO> dtoList = (List<InterestManagementDTO>)resultPager.getResultList();
		if(dtoList == null){
			return null;
		}
		FncPrjPayRegInfoDTO regDto = new FncPrjPayRegInfoDTO();
		for(InterestManagementDTO dto : dtoList){
			regDto.setIntRatType(Integer.parseInt(dto.getIntRatType()));
			regDto.setPayId(dto.getId());
			regDto.setThIntRat(dto.getThIntRat());
			regDto.setThIntTm(dto.getThIntTm());
			regDto.setBscRateId(dto.getBscRateId());
		}
		return this.interestManagementApiService.insertPayRegInfo(regDto);
	}


	/**
	 * 修改支付调息表信息
	 * @param regDto
	 * @return
	 * @throws BaseException
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Long modifyPayRegInfo(FncPrjPayRegInfoDTO reg) throws BaseException {
		//根据支付id得到项目相关信息
		Pager page = new Pager();
		page.setCurrentPage(1);
		page.setEveryPage(10);
		InterestmanagementQueryCondition condition = new InterestmanagementQueryCondition();
		condition.setId(Long.valueOf(0));
		condition.setPayId(reg.getPayId());
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(condition);
		Pager resultPager = this.interestManagementApiService.searchListPage(page);
		List<InterestManagementDTO> dtoList = (List<InterestManagementDTO>)resultPager.getResultList();
		if(dtoList == null){
			return null;
		}
		FncPrjPayRegDTO regDto = new FncPrjPayRegDTO();
		for(InterestManagementDTO dto : dtoList){
			regDto.setIntRatType(Integer.parseInt(dto.getIntRatType()));
			regDto.setPayId(dto.getId());
			regDto.setThIntRat(dto.getThIntRat());
			regDto.setThIntTm(dto.getThIntTm());
			regDto.setBscRateId(dto.getBscRateId());
			regDto.setPreIntRate(dto.getPreIntRate());
			regDto.setPreIntTm(dto.getPreIntTm());
			regDto.setId(reg.getId());
		}
		fncPrjPaySchApiService.modifyFncPrjPayReg(regDto);
		return regDto.getBscRateId();
	}

}
